//
//  HLBaseWebViewController.m
//  JS2WebView
//
//  Created by hongliang on 16/3/7.
//  Copyright (c) 2016年 hongliang. All rights reserved.
//

#import "HLBaseWebViewController.h"

@interface HLBaseWebViewController () <UIWebViewDelegate>
@property(nonatomic, copy)NSString* urlString;

@property(nonatomic, strong)UIActivityIndicatorView* activityIndicator;
@property(nonatomic, strong)UIWebView* webView;
@end

@implementation HLBaseWebViewController

- (instancetype)initWithURL:(NSString*)urlString {
    self = [super init];
    if (self) {
        self.urlString = urlString;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64)];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    _webView.backgroundColor = [UIColor clearColor];
    [_webView setOpaque:NO];
    _webView.userInteractionEnabled = YES;
    [self.view addSubview:_webView];
    
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlString]];
    [_webView loadRequest:request];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)didStartLoading {
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(0, 0, 32.0f, 32.0f)];
        [_activityIndicator setCenter:self.view.center];
        [_activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
        [_activityIndicator setColor:[UIColor blackColor]];
        [self.view addSubview:_activityIndicator];
    }
    
    [_activityIndicator startAnimating];
}

- (void)didFinishLoading {
    [_activityIndicator stopAnimating];
    self.activityIndicator = nil;
}

#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    [self didStartLoading];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [self didFinishLoading];
    
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [self didFinishLoading];
}

@end
